import datetime
import random
import re,jwt

from django.contrib.auth import logout
from django.db.models import Q
from django.http import JsonResponse
from django.views import View
import json
from django_redis import get_redis_connection
from ronglian_sms_sdk import SmsSDK
from xiaoshuo.settings import dev
from xiaoshuo.settings.dev import accId,accToken,appId
from xiaoshuo.utils.md5 import custom_md5
from apps.users.models import User
# 生成jwt token
def generate_jwt_token(user):
    # 要加密的数据 字典
    payload = {
        'id':user.id,
        'username':user.username,
        'mobile':user.mobile,
        'exp':datetime.datetime.now() + datetime.timedelta(seconds=300)
    }
    # 进行加密，生成 jwt token
    token = jwt.encode(payload=payload,key=dev.SECRET_KEY,algorithm='HS256')
    # 返回token
    return  token

"""
发送手机验证码
url:
    sms_code/<mobile>/
methods:
    GET
params:
    参数名     类型  是否必传
    mobile      str     是
response:
    json
    {
        'code': 0,
         'errmsg': '短信验证码发送成功'
    }
"""
class SmsCodeView(View):
    def get(self,request,mobile):
        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return JsonResponse({'code':400,'errmsg':'手机号格式错误'})
        # 要存入的redis库
        redis_conn = get_redis_connection('default')
        sms_sdk = SmsSDK(
            accId=accId,
            accToken=accToken,
            appId=appId,
        )
        # 生成随机字符串
        sms_code = random.randint(1000,9999)
        result = sms_sdk.sendMessage(1, mobile, datas=(sms_code, 5))
        # 把json_str转换为ict
        result_dict = json.loads(result)
        if result_dict['statusCode'] == '111188':
            print(f'短信验证码发送成功：{sms_code}')
        else:
            return JsonResponse({'code':400,'errmsg':'短信验证码发送失败'})
        redis_conn.setex('sms_%s'%mobile,sms_code,60)
        try:
            sms_redis = redis_conn.get('sms_%s'%mobile)
        except Exception:
            return JsonResponse({'code':400,'errmsg':'验证码查询为空'})
        return JsonResponse({'code': 0, 'errmsg': '短信验证码发送成功'})

"""
注册
url:register/
methods:
    POST
params:
    参数名     类型  是否必传
    mobile      str     是
    password    str     是
    sms_code    str     是
response:
    json
    {
        'code':0,
        'errmsg':'注册成功!'
    }
"""
class RegisterView(View):
    def post(self,request):
        json_dict = request.POST
        mobile = json_dict.get('mobile')
        password = json_dict.get('password')
        sms_code = json_dict.get('sms_code')
        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return JsonResponse({'code':400,'errmsg':'手机号格式错误'})
        redis_conn = get_redis_connection('default')
        sms_redis = redis_conn.get('sms_%s' % mobile)
        print(sms_redis)
        if not sms_redis:
            return JsonResponse({'code': 400, 'errmsg': '验证码已过期'})
        if sms_redis.decode() != sms_code:
            return JsonResponse({'code': 400, 'errmsg': '验证码错误'})
        user_info = User.objects.filter(mobile=mobile).first()
        if not user_info:
            username = '游客' + mobile[-4:]
            # 创建用户
            user = User.objects.create(
                username=username,
                password=custom_md5(password),
                photo='',
                mobile=mobile
            )
        return JsonResponse({'code':0,'errmsg':'注册成功!'})

"""
登录
url:login/
methods:
    POST
params:
    参数名     类型  是否必传
    mobile      str     是
    password    str     是
response:
    json
    {
        'code':0,
        'errmsg':'用户%s登陆成功!'%用户名,
        'token':token,
        'user':{
                'username':用户名,
                'user_id':用户id
            }
        }
"""
class LoginView(View):
    def post(self,request):
        json_dict = request.POST
        mobile = json_dict.get('mobile')
        password = json_dict.get('password')
        try:
            user_info = User.objects.get(Q(username=mobile) | Q(mobile=mobile))
        except Exception:
            return JsonResponse({'code':400,'errmsg':'用户不存在'})

        # 判断密码是否正确
        if user_info.password != custom_md5(password):
            return JsonResponse({'code': 400, 'errmsg': '用户名或密码错误'})
        token = generate_jwt_token(user_info)
        return JsonResponse({
            'code':0,
            'errmsg':'用户%s登陆成功!'%user_info.username,
            'token':token,
            'user':{
                'username':user_info.username,
                'user_id':user_info.id
            }
        })

"""
获取个人中心
url:user/
methods:
    GET
params:
    无参数
response:
    json
    {
        'code':0,
        'errmsg':'获取成功!',
        'data':{
                'username': user.username,
                'photo': user.photo,
                'mobile': user.mobile,
                'tatuls': user.tatuls
            }
    }
"""
class UserView(View):
    def get(self,request):
        try:
            user = User.objects.get(id=1)
            data = {
                'username': user.username,
                'photo': user.photo,
                'mobile': user.mobile,
                'tatuls': user.tatuls
            }
        except Exception:
            return JsonResponse({'code': 400, 'errmsg': '用户未登录!'})
        return JsonResponse({'code':0,'errmsg':'获取成功!','data':data})

"""
退出登录
url:logout/
methods:
    DELETE
params:
    无
response:
    {
        'code':0,
        'errmsg':'退出成功!'
    }
"""
class LogoutView(View):
    def delete(self,request):
        logout(request=request)
        return JsonResponse({'code':0,'errmsg':'退出成功!'})